package com.gr.springboot_shiro.controller;

import com.gr.springboot_shiro.entity.User;
import com.gr.springboot_shiro.service.UserService;
import com.gr.springboot_shiro.utils.VerifyCodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("user")
public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 生成图片验证码
     *
     * @param session
     * @param response
     * @throws IOException
     */
    @RequestMapping("getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        String code = VerifyCodeUtils.generateVerifyCode(4);
        session.setAttribute("code", code);
        ServletOutputStream os = response.getOutputStream();
        VerifyCodeUtils.outputImage(220, 60, os, code);
    }

    @RequestMapping("/login")
    public String login(String username, String password, String code, HttpSession session) {
        //验证码验证
        String codes = (String) session.getAttribute("code");
        //验证码输入正确则开始认证
        try {
            if (!codes.isEmpty()&& codes.equalsIgnoreCase(code)) {
                System.out.println("----login");
                Subject subject = SecurityUtils.getSubject();

                //认证
                subject.login(new UsernamePasswordToken(username, password));
                return "redirect:/index.jsp";
            } else {
                throw new RuntimeException("验证码错误！");
            }
        } catch (UnknownAccountException e) {
            System.out.println("账号错误哦");
        } catch (IncorrectCredentialsException p) {
            System.out.println("密码错误");
        } catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

        return "redirect:/login.jsp";
    }

    @RequestMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    @RequestMapping("/register")
    public String register(String username, String password) {
        User user = new User();
        user.setPassword(password).setUsername(username);
        userService.registerUser(user);
        return "redirect:/login.jsp";
    }
}
